package com.itsu.controller;


import com.github.pagehelper.PageInfo;
import com.itsu.domain.Catalog;
import com.itsu.domain.Company;
import com.itsu.domain.Question;
import com.itsu.service.CatalogService;
import com.itsu.service.CompanyService;
import com.itsu.service.Impl.CatalogServiceImpl;
import com.itsu.service.Impl.CompanyServiceImpl;
import com.itsu.service.Impl.QuestionServiceImpl;
import com.itsu.service.QuestionService;
import com.itsu.utils.BeanUtil;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@WebServlet("/store/question")
public class QuestionController extends HttpServlet {

    private QuestionService questionService = new QuestionServiceImpl();
    private CompanyService companyService = new CompanyServiceImpl();
    private CatalogService catalogService = new CatalogServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
        String operation = req.getParameter("operation");
        if ("list".equals(operation)) {
            showList(req, resp);
        } else if ("toAdd".equals(operation)) {
            toAdd(req, resp);
        } else if ("save".equals(operation)) {
            save(req, resp);
        } else if ("toEdit".equals(operation)) {
            toEdit(req, resp);
        } else if ("edit".equals(operation)) {
            edit(req, resp);
        } else if ("delete".equals(operation)) {
            delete(req, resp);
        } else if ("downLoadExcel".equals(operation)) {
            downLoadExcel(req, resp);
        }
    }

    private void showList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNum = 1;
        int pageSize = 10;
        if (!StringUtils.isNullOrEmpty(req.getParameter("page"))) {
            pageNum = Integer.parseInt(req.getParameter("page"));
        }
        PageInfo<Question> pageInfo = questionService.findAll(pageNum, pageSize);

        req.setAttribute("page", pageInfo);

        req.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(req, resp);
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        req.setAttribute("companyList", companyList);
        req.setAttribute("catalogList", catalogList);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(req, resp);
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Question question = null;
        String picture = null;

        if (ServletFileUpload.isMultipartContent(req)) {
            try {
                DiskFileItemFactory dff = new DiskFileItemFactory();
                ServletFileUpload sfu = new ServletFileUpload(dff);
                List<FileItem> fileItems = sfu.parseRequest(req);

                for (FileItem fileItem : fileItems) {
                    if (!fileItem.isFormField()) {
                        if (fileItem.getSize() != 0) {
                            String fileNo = UUID.randomUUID().toString().replaceAll("-", "");
                            String dir = req.getServletContext().getRealPath("upload");
                            char a = fileNo.charAt(0);
                            char b = fileNo.charAt(1);
                            char c = fileNo.charAt(2);
                            dir = dir + "/" + a + "/" + c + "/" + b;
                            File parentDir = new File(dir);
                            if (!parentDir.exists()) {
                                parentDir.mkdirs();
                            }

                            fileItem.write(new File(parentDir, fileNo));
                            picture = a + "/" + c + "/" + b + "/" + fileNo;
                            System.out.println(picture);

                        }
                    }
                }

                question = BeanUtil.fillBean(fileItems, Question.class);
                question.setPicture(picture);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            question = BeanUtil.fillBean(req, Question.class);
        }


        question.setId(UUID.randomUUID().toString());
        question.setCreateTime(new Date());

        questionService.save(question);

        resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");
    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Question question = questionService.findById(id);

        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        req.setAttribute("companyList", companyList);
        req.setAttribute("catalogList", catalogList);
        req.setAttribute("question", question);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(req, resp);
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Question question = null;
        String picture = null;
        if (ServletFileUpload.isMultipartContent(req)) {
            try {
                DiskFileItemFactory dff = new DiskFileItemFactory();
                ServletFileUpload sfu = new ServletFileUpload(dff);
                List<FileItem> fileItems = sfu.parseRequest(req);

                question = BeanUtil.fillBean(fileItems, Question.class);

                    for (FileItem fileItem : fileItems) {
                        if(!fileItem.isFormField()) {
                            if(fileItem.getSize() != 0) {
                                String fileNo = UUID.randomUUID().toString().replaceAll("-", "");
                                String dir = req.getServletContext().getRealPath("upload");
                                char a = fileNo.charAt(0);
                                char b = fileNo.charAt(1);
                                char c = fileNo.charAt(2);
                                dir = dir + "/" + a + "/" + c + "/" + b;
                                File parentDir = new File(dir);
                                if (!parentDir.exists()) {
                                    parentDir.mkdirs();
                                }

                                fileItem.write(new File(parentDir, fileNo));
                                picture = a + "/" + c + "/" + b + "/" + fileNo;
                                System.out.println(picture);
                                question.setPicture(picture);
                            }
                        }
                    }
                System.out.println(question);
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            question  = BeanUtil.fillBean(req, Question.class);
            System.out.println(question);
        }

        questionService.update(question);

        resp.sendRedirect(req.getContextPath() + "/store/question?operation=list&time"+ new Date());
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Question question = BeanUtil.fillBean(req, Question.class);
        questionService.delete(question);

        resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");
    }

    private void downLoadExcel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String excelId = UUID.randomUUID().toString().replaceAll("-", "") + ".xlsx" ;

        ServletContext sc = req.getServletContext();

        String mimeType = sc.getMimeType(excelId);

        resp.setHeader("Content-Type", mimeType);
        resp.setHeader("Content-Disposition", "attachment;filename=" + excelId);

        String realPath = sc.getRealPath("/template/test_template.xlsx");

        ServletOutputStream outputStream = resp.getOutputStream();

        questionService.downLoadExcel(outputStream, realPath);
    }
}

